from symbide import ModuleManager, PATHS

from Gnuplot import Gnuplot
from os import remove
from os.path import exists
from time import sleep
from symbide.src.utils import createUniquePath

class SymbideGnuplot(Gnuplot):
    def __init__(self, *args):
        Gnuplot.__init__(self)
        format = 'svg'
        self.path = createUniquePath(PATHS['temp_pictures'], 'gnuplot', '.'+format)
        self('set terminal %s'%format)
        self('set output "%s"'%self.path)
        for i in args:
            self(i)
        
    def toxml(self):
        self('unset multiplot')
        p = self.path+'control'
        self('set output "%s"'%p)
        i = 0
        while not exists(p):
            sleep(0.05)
            i+=1
            if i>10000:
                break
        remove(p)
        return '<img src="%s"/>'%self.path

    def _convert(self, value):            
        if isinstance(value, (int, float)):
            return value
        elif ModuleManager.hasModule('numpy'):
            from numpy import ndarray
            if isinstance(value, ndarray):
                return value
        elif isinstance(value, (list, tuple)):
            buf=[]
            for i in value:
                buf.append(self._convert(i))
            return buf
        elif ModuleManager.hasModule('sympy'):
            from sympy import Number, Integer
            if isinstance(value, Integer):
                return int(value)
            if isinstance(value, Number):
                return float(value)
        else:
            try:
                return float(value)
            except:
                try:
                    self.convert(list(value))
                except:
                    return value
    
    def plot(self, *items, **keyw):
        Gnuplot.plot(self, *self._convert(items), **keyw)
        
    def splot(self, *items, **keyw):
        Gnuplot.splot(self, *self._convert(items), **keyw)